#include "sig.h"
static int thisTime = 0;
static PSeqListType thisPUserTable = NULL;
static PSeqListType thisPContactTable = NULL;
static PUserType *thisPUser = NULL;
static PSeqListType* thisPContactList = NULL;

void ExitServer(int arg)
{
    //保存用户
    SaveUserTable(thisPUserTable);
    //保存联系人
    SaveContactTable(thisPContactTable);
    raise(SIGKILL);
}

void UpdateServer(int arg)
{
    //更新用户
    SaveUserTable(thisPUserTable);
    //更新联系人
	SaveContactTable(thisPContactTable);

    //重置定时器
    alarm(thisTime);

}

//捕获ctrl+c信号 退出时保存文件
void SignalExitServer(PSeqListType pUserTable, PSeqListType pContactTable)
{
    thisPUserTable = pUserTable;
    thisPContactTable=pContactTable;
    signal(SIGINT, ExitServer);
}

//捕获时钟信号 每过10s更新到文件
void SignalUpdateServer(PSeqListType pUserTable, PSeqListType pContactTable, int time)
{
    thisTime = time;
    alarm(thisTime);
    thisPUserTable = pUserTable;
    thisPContactTable=pContactTable;
    signal(SIGALRM, UpdateServer);
}

void ExitUser(int arg)
{
    //样式还原
    printf("\33[0m");

    //用户登出
    RequestLogout(*thisPUser);
    
    //资源释放
    if(thisPUser != NULL && *thisPUser != NULL)
    {
        UserFree(thisPUser);
    }
    if(thisPContactList != NULL && *thisPContactList != NULL)
    {
        ContactFree(thisPContactList);
    }
    //3秒后退出
    ShowExit(3);
    raise(SIGKILL);
}

//捕获ctrl+c信号 退出时资源释放，用户登出
void SignalExitUser(PUserType *pUser, PSeqListType* pContactList)
{
    thisPUser = pUser;
    thisPContactList=pContactList;
    signal(SIGINT, ExitUser);
}